package com.rub.android.ui.activity

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.rub.android.R
import com.rub.android.adapter.TagsAdapter
import com.rub.android.widget.InjectorUtil
import com.rub.android.widget.RetrofitServiceApi
import com.rub.android.extension.showToast
import com.rub.android.utils.ResponseHandler
import com.rub.android.utils.RetrofitHelper
import com.rub.android.utils.logI
import com.rub.android.viewmodel.TagsViewModel
import com.trello.rxlifecycle.components.support.RxAppCompatActivity
import kotlinx.android.synthetic.main.activity_tags.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers


class TagsActivity : RxAppCompatActivity() {

    // private val viewModel by lazy { ViewModelProvider(this).get(TagsViewModel::class.java) }
    private val viewModel by lazy {
        ViewModelProvider(
            this,
            InjectorUtil.getTagsViewModelFactory()
        ).get(TagsViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tags)
        viewModel.onRefresh()
        observe()
    }


    private fun observe() {
        if (!viewModel.responseData.hasObservers()) {
            viewModel.responseData.observe(this, Observer { result ->
                val response = result.getOrNull()
                if (response == null) {
                    ResponseHandler.getFailureTips(result.exceptionOrNull()).showToast()
                    return@Observer
                }

                lvTag.adapter = TagsAdapter(response.tags, this)

                lvTag.setOnItemClickListener { parent, view, position, id ->
                    logI("ListViewActivity","点击位置:${position}")
                }

            })
        }

    }


    private fun listTags() {
        RetrofitServiceApi(RetrofitHelper())
            ?.listTags()
            ?.compose(this.bindToLifecycle())
            ?.subscribeOn(Schedulers.io())
            ?.map { it?.tags }
            ?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe({ tags ->
                if (tags != null) {
                    for (tag in tags)
                        Log.i("TagsActivity", "tag:$tag ")
                }
            }) { throwable -> initEmptyView() }
    }

    private fun initEmptyView() {
        Log.i("TagsActivity", "initEmptyView: ")
    }

}